package authority

import (
	"cgs-server/server"
	"cgs-server/server/base"
	"cgs-server/server/model"
	"errors"
)

type AuthorityService interface {
	base.Service

	// 获取应用权限列表
	ListAppAuth() (interface{}, error)
}

func NewAuthorityService() AuthorityService {
	authRepo := NewAuthorityRepository()
	return &authorityService{
		authRepo:    authRepo,
		ServiceImpl: base.ServiceImpl{Repo: authRepo},
	}
}

type authorityService struct {
	base.ServiceImpl
	authRepo AuthorityRepository
}

// 获取后台权限列表
func (a *authorityService) List(mdl *model.DataUserModel) (interface{}, error) {
	/*// api 权限
	var apiAuths []*model.ApiAuthority
	//var paths []string
	for _, v := range server.GetAllAuthorities2() {
		apiAuths = append(apiAuths, v)
		//paths = append(paths, v.ApiPath)
	}
	// menu 权限
	menuAuths, err := a.authRepo.FindAllMenuAuth(mdl)
	if err != nil {
		return nil, err
	}

	auths := model.Authorities{
		ApiAuths:  apiAuths,
		MenuAuths: menuAuths,
	}*/
	auths := server.GetAllAuthorities()
	return auths, nil
}

func (a *authorityService) ListAppAuth() (interface{}, error) {
	auths := server.GetAppFormAuth()
	return auths, nil
}

// 添加 menu 权限
func (a *authorityService) Save(mdl *model.DataUserModel) error {
	if menuAuth, ok := mdl.Data.(*model.MenuAuthority); ok {
		if err := a.Init(); err != nil {
			return err
		}
		//menuAuth.Name 不允许重复
		findResult, err := a.authRepo.FindByMenuName(menuAuth.Name)
		if err != nil {
			return err
		}
		if findResult != nil {
			return errors.New("Name is not allowed duplicated")
		}
		return a.authRepo.Insert(mdl)
	} else {
		return errors.New("MenuAuth type error.")
	}
}

// 修改 menu 权限
func (a *authorityService) Update(mdl *model.DataUserModel) error {
	return a.authRepo.Update(mdl)
}

// 删除 menu 权限
func (a *authorityService) Remove(mdl *model.DataUserModel) error {
	return a.authRepo.Delete(mdl)
}
